<template>
  <div>
    <!-- 搜索建议 -->
    <van-cell  icon="search"  v-for="(suggests, index) in searchSug" :key="index">
      <div slot="title" @click="$emit('search', suggests)" v-html="textActive(suggests)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSug } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  data () {
    return {
      searchSug: [],
      timeId: 0
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      // handler () {
      //   clearTimeout(this.timeId)
      //   this.timeId = setTimeout(_ => {
      //     this.getSearchSugList(this.searchText)
      //   }, 800)
      //   console.log(debounce)
      // },
      handler: debounce(function () {
        this.getSearchSugList(this.searchText)
      }, 800),
      immediate: true // 实例初始化时,自调用一次
    }
  },
  methods: {
    async getSearchSugList (searchText) {
      try {
        const { data: res } = await getSearchSug(this.searchText)
        this.searchSug = res.data.options
      } catch (err) {
        console.log(err.response)
      }
    },
    textActive (txt) {
      const reg = new RegExp(this.searchText, 'gi')
      return txt.replace(reg, '<span style="color: red">' + this.searchText + '</span>')
    }
  }
}
</script>

<style scoped>

</style>
